package edu.ccut.saturn.studio.dialog.webcontextdialog;

import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.TableItem;

import edu.ccut.saturn.studio.dialog.SelectionCandidate;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnWebContextParameter;

public class MyCellModifierWebContext implements ICellModifier {
	
	private TableViewer tableViewer;

	public MyCellModifierWebContext(TableViewer tableViewer){
		this.tableViewer = tableViewer;
	}
	
	public boolean canModify(Object arg0, String arg1) {
		return true;
	}

	public Object getValue(Object element, String property) {
		SaturnWebContextParameter o = (SaturnWebContextParameter) element;
		if (property.equals("id")) {
			return o.getId();
		} else if (property.equals("key")) {
			return o.getKey();
		} else if (property.equals("scope")) {
			return getScopeIndex(o.getScope());
		} else if (property.equals("newKey")){
			return o.getNewKey();
		} else if (property.equals("newScope")){
			return getScopeIndex(o.getNewScope());
		}
			throw new RuntimeException("" + property); 
	}
	
	private int getScopeIndex(String scope) {
		for (int i = 0; i < SelectionCandidate.scopes.length; i++) {
			if (SelectionCandidate.scopes[i].equals(scope))
				return i;
		}
		return -1;
	}
	
	public void modify(Object element, String property, Object value) {
		TableItem item = (TableItem) element;
		SaturnWebContextParameter o = (SaturnWebContextParameter) item.getData();
		if (property.equals("key")) {
			String key = (String) value;
			o.setKey(key);
		} else if (property.equals("scope")) {
			Integer comboIndex = (Integer) value;
			String scope = SelectionCandidate.scopes[comboIndex];
			o.setScope(scope);
		} else if (property.equals("newKey")) {
			String newKey = (String) value;
			o.setNewKey(newKey);
		} else if(property.equals("newScope")){
			Integer comboIndex = (Integer) value;
			String newScope = SelectionCandidate.scopes[comboIndex];
			o.setNewScope(newScope);
		} 
		else {
			throw new RuntimeException("" + property); 
		}
		tableViewer.update(o, null);
	}
}